package com.chengyu.core.controller.common;



import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Tellsea
 * @date 2021/07/01
 */
@RestController
@RequestMapping("/au/weiXin")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AuWeiXinController {
//
//    private final ISysUserService userService;
//    private final SysPermissionService permissionService;
//    private final TokenService tokenService;
//    private final SysUserRoleMapper sysUserRoleMapper;
//    private final SysLoginService loginService;
//    private final WeiXinProperties weiXinProperties;
//
//    @ApiOperation("登录检查")
//    @GetMapping("beforeLogin")
//    public AjaxResult beforeLogin() {
//        return AjaxResult.success("检查成功");
//    }
//
//    @ApiOperation("微信授权登录")
//    @GetMapping("login")
//    public AjaxResult login() {
//        try {
//            String redirect_uri = URLEncoder.encode(weiXinProperties.getCallBackUrl(), "UTF-8");
//            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
//                    + "appid=" + weiXinProperties.getAppId()
//                    + "&redirect_uri=" + redirect_uri
//                    + "&response_type=code"
//                    + "&scope=snsapi_userinfo"
//                    + "&state="
//                    + "&connect_redirect=1#wechat_redirect";
//            return AjaxResult.success("请求成功", url);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error("微信授权登录失败");
//        }
//    }
//
//    @ApiOperation("回调地址")
//    @GetMapping("callBack")
//    public void callBack(HttpServletRequest request, HttpServletResponse response) {
//        String code = request.getParameter("code");
//        String state = request.getParameter("state");
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
//                + "appid=" + weiXinProperties.getAppId()
//                + "&secret=" + weiXinProperties.getSecret()
//                + "&code=" + code
//                + "&grant_type=authorization_code";
//        JSONObject jsonObject = JSON.parseObject(HttpUtil.get(url));
//        Integer errcode = jsonObject.getInteger("errcode");
//        if (errcode != null) {
//            String errmsg = jsonObject.getString("errmsg");
//            throw new CustomException("【微信回调错误】错误码：" + errcode + "，错误信息：" + errmsg);
//        }
//        String openid = jsonObject.getString("openid");
//        String access_token = jsonObject.getString("access_token");
//        String refresh_token = jsonObject.getString("refresh_token");
//        Integer expires_in = jsonObject.getInteger("expires_in");
//
//        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
//                + "access_token=" + access_token
//                + "&openid=" + openid
//                + "&lang=zh_CN";
//        // 获取微信用户信息
//        JSONObject userInfo = JSON.parseObject(HttpUtil.get(infoUrl));
//        String country = userInfo.getString("country");
//        String province = userInfo.getString("province");
//        String city = userInfo.getString("city");
//        Integer sexValue = userInfo.getInteger("sex");
//        String nickName = userInfo.getString("nickname");
//        String avatar = userInfo.getString("headimgurl");
//        String language = userInfo.getString("language");
//        String sex;
//        if (IntegerUtils.eq(sexValue, 1)) {
//            sex = "0";
//        } else if (IntegerUtils.eq(sexValue, 2)) {
//            sex = "1";
//        } else {
//            sex = "2";
//        }
//        List<SysUser> list = userService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openid));
//        String token;
//        SysUser user = null;
//        if (CollectionUtils.isEmpty(list)) {
//            // 注册用户
//            SysUser entity = new SysUser();
//            entity.setOpenId(openid);
//            entity.setUserName(openid);
//            entity.setNickName(nickName);
//            entity.setAvatar(avatar);
//            entity.setDeptId(0L);
//            entity.setSex(sex);
//            entity.setRoleIds(new Long[]{RoleConstants.USER.getRoleId()});
//            userService.insertUser(entity);
//            SysUser sysUser = userService.selectUserByUserName(entity.getUserName());
//            LoginUser loginUser = new LoginUser(sysUser, permissionService.getMenuPermission(sysUser));
//            token = tokenService.createToken(loginUser);
//        } else if (list.size() == 1) {
//            // 更新用户
//            user = list.get(0);
//            user.setNickName(nickName);
//            userService.updateById(user);
//            SysUser sysUser = userService.selectUserByUserName(user.getUserName());
//            List<SysRole> roles = sysUser.getRoles();
//            List<String> roleKeys = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
//            if (!roleKeys.contains(RoleConstants.USER.getRoleKey())) {
//                // 给角色用户
//                sysUserRoleMapper.insert(new SysUserRole().setUserId(user.getUserId()).setRoleId(RoleConstants.USER.getRoleId()));
//                sysUser = userService.selectUserByUserName(user.getUserName());
//            }
//            LoginUser loginUser = new LoginUser(sysUser, permissionService.getMenuPermission(sysUser));
//            token = tokenService.createToken(loginUser);
//        } else {
//            throw new CustomException("数据异常：OpenId存在多个");
//        }
//        try {
//            // 重定向到登录，自动跳转首页
//            String redirectUrl = weiXinProperties.getRedirectLoginUrl() + "?token=" + token;
//            response.sendRedirect(redirectUrl);
//        } catch (IOException e) {
//            e.printStackTrace();
//            throw new CustomException("【微信回调错误】重定向地址错误");
//        }
//    }
//
//    @ApiOperation("获取用户信息")
//    @GetMapping("getInfo")
//    public AjaxResult getInfo() {
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        SysUser user = loginUser.getUser();
//        Set<String> permission = permissionService.getRolePermission(user);
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("user", user);
//        ajax.put("roles", permission);
//        ajax.put("permissions", permissionService.getMenuPermission(user));
//        return ajax;
//    }
}

